// Fill out your copyright notice in the Description page of Project Settings.


#include "CharacterZD/Core/TowerAIController.h"

#include "EngineUtils.h"
#include "CharacterZD/Core/MonsterZD.h"
#include "CharacterZD/Core/TowerZD.h"
#include "Components/ArrowComponent.h"
#include "TF_20240717/StoneDefenceUtils.h"


ATowerAIController::ATowerAIController() : HeartbeatDiagnosis(0.0f)
{
	PrimaryActorTick.bCanEverTick = true;
}

void ATowerAIController::BeginPlay()
{
	Super::BeginPlay();
	
}

void ATowerAIController::BTService_FindTarget()
{
	// 清空数组
	MonsterArray.Empty();
	if (ATowerZD* Tower = GetPawn<ATowerZD>())
	{
		if (Tower->IsActive())
		{
			for (TActorIterator<AMonsterZD> it(GetWorld(), AMonsterZD::StaticClass()); it; ++it)
			{
				AMonsterZD* TheCharacter = *it;
				if (TheCharacter && TheCharacter->IsActive())
				{
					FVector TDistance = GetPawn()->GetActorLocation() - TheCharacter->GetActorLocation();
					if (TDistance.Size() < 1600.0f)
					{
						MonsterArray.Add(TheCharacter);
					}
				}
			}

			
			AttackTarget(Target.Get());
			// Tower->bAttack = MonsterArray.Num() > 0 ? true : false;
		}
	}
}

void ATowerAIController::AttackTarget(ARuleCharacterZD* NewTarget)
{
	Super::AttackTarget(NewTarget);
	ATowerZD* Tower =  Cast<ATowerZD>(GetPawn());
	Tower->bAttack = MonsterArray.Num() > 0 ? true : false;
}

void ATowerAIController::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);

	// 定时查找范围内目标
	HeartbeatDiagnosis += DeltaTime;
	if (HeartbeatDiagnosis >= 0.5f)
	{
		BTService_FindTarget();
		HeartbeatDiagnosis = 0.0f;
	}

	// 旋转防御塔朝向
	if (MonsterArray.Num())
	{
		if (ATowerZD* Towers = GetPawn<ATowerZD>())
		{
			if (!Target.IsValid())
			{
				Target = Cast<ARuleCharacterZD>(FindTarget());
			}

			if (Target.IsValid())
			{
				// Towers->TowerRotator = FRotationMatrix::MakeFromX(Target->GetActorLocation() - GetPawn()->GetActorLocation()).Rotator();
				// if (GetPawn()->GetActorRotation() != FRotator::ZeroRotator)
				// {
				// 	Towers->TowerRotator -= GetPawn()->GetActorRotation();
				// }

				Towers->SetDirection(Target->GetActorLocation() - Towers->GetActorLocation());
			}



			
		}
		
	}
}

AActor* ATowerAIController::FindTarget()
{
	return StoneDefenceUtils::FindTargetRecently(MonsterArray, GetPawn()->GetActorLocation());
}

